// 3. useBase64
import { type App } from "vue";

interface IuseBase64 {
  (el: HTMLImageElement): string;
  install: (app: App, name: string) => void;
}

const toBase64: IuseBase64 = (el) => {
  const canvas: HTMLCanvasElement = document.createElement("canvas");
  const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
  canvas.width = el.width;
  canvas.height = el.height;
  ctx.drawImage(el, 0, 0, el.width, el.height);
  const dataURL: string = canvas.toDataURL("image/png");
  return dataURL;
};

toBase64.install = (app, directiveName = "base64") => {
  app.directive(directiveName, {
    mounted(el: HTMLImageElement, binding: any) {
      const fn = binding.value;
      if (fn) {
        el.onload = () => {
          fn(el, toBase64(el));
        };
      }
    },
  });
};;

export const useBase64 = toBase64;
export default useBase64;
